<template>
  <view class="page">
    <view class="header" v-if="userInfo">
      <image class="avatar" :src="getShowImage(userInfo.userIcon)" v-if="getShowImage(userInfo.userIcon)"></image>
      <view class="right">
        <view class="nick-name">{{ userInfo.nickName }}</view>
        <!--				已开通会员-->
        <view class="member-status" v-if="userInfo.memberInfo">
          <!--					会员属性名称-->
          <text>{{ userInfo.memberInfo.memberProName }}</text>
          <!--					会员到期时间-->
          <view v-if="userInfo.memberInfo.expireDate" style="margin-left: 20rpx">
            <text>{{ userInfo.memberInfo.expireDate }}</text>
            <text>到期</text>
          </view>
        </view>
        <!--				未开通会员-->
        <view class="member-status" v-else>未开通会员</view>
      </view>
    </view>
    <!--		会员价格列表-->
    <view class="member-list-wrapper">
      <view class="member-list">
        <!--				首充特惠-->
        <!--        <view class="member-item primary">-->
        <!--          <view class="title">首充特惠</view>-->
        <!--          <view class="price">-->
        <!--            <view class="unit">￥</view>-->
        <!--            <view class="number">19.8</view>-->
        <!--          </view>-->
        <!--          <view class="average-price"> 0.64元/天 </view>-->
        <!--        </view>-->
        <view
          class="member-item normal"
          v-for="item in memberLevelDetail.levelList"
          :key="item.proLevelCode"
          @click="currentSelectMemberItem = item"
          :class="item.proLevelCode === currentSelectMemberItem.proLevelCode ? 'active' : 'inactive'"
        >
          <view class="title">{{ item.title }}</view>
          <!--						原价（针对存在价格减免的情况）-->
          <view class="price-container">
            <view class="origin-price price" v-if="handleCouponPrice(item.proLevelPrice) !== item.proLevelPrice">
              <view class="unit">￥</view>
              <view class="number">{{ handleMoney(item.proLevelPrice) }} </view>
            </view>
            <!--						实际价格-->
            <view class="actual-price price">
              <view class="unit">￥</view>
              <view class="number">{{ handleMoney(handleCouponPrice(item.proLevelPrice)) }} </view>
            </view>
          </view>
          <!--					平均每天价格-->
          <view class="average-price"> {{ handleMoney(handleCouponPrice(item.proLevelPrice) / item.dayCount) }}元 / 天 </view>
        </view>
      </view>
      <!--			优惠券-->
      <view class="coupon" style="margin-top: 30rpx">
        <coupon-banner
          :no-coupon="noCoupon"
          @handlePopupOpen="$refs.couponPopup.handlePopupOpen()"
          :current-select="currentSelectCouponItem"
        ></coupon-banner>
      </view>
      <!--			会员协议-->
      <view
        class="agreement"
        @click="
          () => {
            if (!agree) {
              $refs.agreement.open()
            } else {
              agree = false
            }
          }
        "
      >
        <radio :checked="agree" class="radio"></radio>
        <view class="text">
          <text class="normal">我已阅读并同意</text>
          <text class="primary">校务行 | 督学刷题会员服务协议</text>
        </view>
      </view>
    </view>
    <!--		轮播图-->
    <view style="margin-top: 20rpx">
      <image
        class="swiper"
        v-for="item in bannerList"
        :key="item.id"
        :src="getShowImage(item.imagePath)"
        @click="bannerClick(item)"
        mode="widthFix"
      ></image>
    </view>
    <!--		会员海报-->
    <image class="poster" :src="getShowImage(memberLevelDetail.detailsInfo)" mode="widthFix"></image>
    <agreement ref="agreement" @agree="agree = true" :content="memberLevelDetail.memberProtocol"></agreement>
    <!--		底部总价 / 支付 按钮 -->
    <view class="footer" v-if="currentSelectMemberItem">
      <view class="total-price">
        <view class="content">
          <view class="text">实付：</view>
          <view class="unit">￥</view>
          <view class="number">{{ handleMoney(handleCouponPrice(currentSelectMemberItem.proLevelPrice)) }} </view>
        </view>
      </view>
      <view class="pay-btn" @click="handlePay"> 立即支付</view>
    </view>
    <!--		开通会员后的弹窗-->
    <popup ref="afterOpenVipPopup"></popup>
    <!--			优惠券-->
    <couponPopup
      ref="couponPopup"
      :no-coupon.sync="noCoupon"
      @select="
        (val) => {
          currentSelectCouponItem = val
        }
      "
    ></couponPopup>
  </view>
</template>

<script>
import store from "../../store"
import { userActionType } from "../../store/modules/user"
import { checkBindPhone, getShowImage, handleMoney, showModal, showToast } from "../../utils"
import agreement from "./components/agreement.vue"
import request from "../../utils/request"
import pay from "../../utils/pay"
import { dictActionType } from "../../store/modules/dict"
import popup from "../../components/popup/index.vue"
import shareInfo from "../../utils/shareInfo"
import couponPopup from "./components/coupon/couponPopup.vue"
import CouponBanner from "./components/coupon/couponBanner.vue"

export default {
  components: { CouponBanner, agreement, popup, couponPopup },
  data() {
    return {
      userInfo: null,
      agree: false, //用户是否同意服务协议
      memberLevelDetail: {
        levelList: [], //会员套餐列表
        memberProtocol: "", //会员协议内容
        detailsInfo: "", //会员介绍海报
      },
      currentSelectMemberItem: null, //当前选中的会员套餐
      afterOpenVipPopupImage: "", //开通会员后的弹窗图片
      currentSelectCouponItem: null, //当前选中的优惠券
      noCoupon: false, //是否有优惠券
      redirectUrl: "",
      bannerList: [], //轮播图列表
    }
  },
  onShow() {
    this.init()
  },
  async onLoad(query) {
    if (query.redirectUrl) {
      this.redirectUrl = decodeURIComponent(query.redirectUrl)
    }
    this.afterOpenVipPopupImage = await store.dispatch(dictActionType.actions.getDictValueByLabel, {
      label: "开通会员后的弹窗",
      type: "staticImageUrl",
    })
    //获取轮播图
    request({
      url: "rotationChart/page",
      data: {
        position: 4,
        current: 1,
        size: -1,
      },
      showLoading: true,
      errorHandle: true,
    }).then((data) => {
      this.bannerList = data.records
    })
  },
  methods: {
    handleMoney,
    getShowImage,
    async init() {
      this.userInfo = await store.dispatch(userActionType.action.userInfo)
      this.memberLevelDetail = await request({
        errorHandle: true,
        showLoading: true,
        url: "memberLevel/getMemberPackage",
      })
      //默认选中第一个
      this.currentSelectMemberItem = this.memberLevelDetail.levelList[0]
      //获取优惠券列表
      this.$nextTick(() => {
        this.$refs.couponPopup.getCouponList()
      })
    },
    async handlePay() {
      //判断是否有绑定手机号码
      if (!(await checkBindPhone())) return
      if (!this.agree) {
        //弹出用户协议供用户勾选
        this.$refs.agreement.open()
        return
      }
      try {
        //创建订单
        const res = await request({
          url: "memberLevel/buyMember",
          data: {
            proLevelCode: this.currentSelectMemberItem.proLevelCode,
            userCouponId: this.currentSelectCouponItem.userCouponId,
          },
          showLoading: true,
        })
        //发起支付
        await pay.handlePay(res)

        // 支付之后的逻辑
        let that = this
        async function afterPay() {
          //配置了跳转链接跳转过去
          if (that.redirectUrl) {
            uni.reLaunch({
              url: that.redirectUrl,
            })
            //返回上一页
          } else {
            uni.navigateBack({
              delta: 1,
            })
          }
        }
        //查询系统参数是否需要展示付款成功后的弹框
        const showPopup = await request({
          showLoading: true,
          url: "sysPam/getSysParam",
          data: {
            pamCode: "showAfterOpenVipPopup",
          },
        })
        //展示开通会员后的弹框
        if (showPopup.pamValue === "是") {
          this.$refs.afterOpenVipPopup.addPopupItem(this.afterOpenVipPopupImage, () => {
            afterPay()
          })
        } else {
          if (
            await showModal({
              title: "恭喜",
              content: "会员开通成功",
							showCancel: false,
            })
          ) {
            await afterPay()
          }
        }
      } catch (e) {
        //用户取消支付跳转到订单列表页面
        if (e === "requestPayment:fail cancel") {
          uni.navigateTo({
            url: "/pages/mine/orderList/index",
          })
          return
        }
        showToast.default(e)
        console.log(e, "error")
      }
    },
    //计算优惠后的实际价格
    handleCouponPrice(originPrice) {
      //只有选择了优惠券才减免价格
      if (this.currentSelectCouponItem) {
        //价格减免策略
        if (this.currentSelectCouponItem.priceStrategy === "0") {
          //防止计算出负数的价格
          return originPrice - this.currentSelectCouponItem.price < 1 ? 0 : originPrice - this.currentSelectCouponItem.price
          //折扣策略
        } else if (this.currentSelectCouponItem.priceStrategy === "1") {
          const actualPrice = originPrice * this.currentSelectCouponItem.discountRate
          //防止计算出的价格为0
          return actualPrice < 1 ? 1 : actualPrice
          //满减策略
        } else if (this.currentSelectCouponItem.priceStrategy === "2") {
          if (originPrice >= this.currentSelectCouponItem.fullYuan && this.currentSelectCouponItem.fullYuan !== 0) {
            //防止计算出负数的价格
            return originPrice - this.currentSelectCouponItem.price < 1 ? 0 : originPrice - this.currentSelectCouponItem.price
          }
        }
      }
      return originPrice
    },
    //轮播图点击
    async bannerClick(item) {
      //无跳转逻辑
      if (!item.jumpType || item.jumpType === "NONE") return
      //跳转到小程序
      if (item.jumpType === "Applet" && item.appid) {
        uni.navigateToMiniProgram({
          appId: item.appid,
          path: item.jumpPath,
        })
        return
      }
      //跳转站内页面
      if (item.jumpType === "Instation" && item.jumpPath) {
        uni.navigateTo({
          url: item.jumpPath,
        })
        uni.switchTab({
          url: item.jumpPath,
        })
        return
      }
      //跳转h5页面
      if (item.jumpType === "H5" && item.jumpPath) {
        uni.navigateTo({
          url: "/pages/web-view/web-view?path=" + encodeURIComponent(item.jumpPath),
        })
        return
      }
    },
  },
  //右上角分享
  async onShareAppMessage() {
    return await shareInfo.getTJGShareInfo({
      path: "/pages/mine/vipList",
    })
  },
}
</script>

<style lang="scss" scoped>
.page {
  background: var(--gray-background-color);
  min-height: 100vh;
  box-sizing: border-box;
  padding-bottom: calc(env(safe-area-inset-bottom) + 130rpx);

  .header {
    background: #3e3e3e;
    padding: {
      top: 30rpx;
      left: 30rpx;
      right: 30rpx;
      bottom: 60rpx;
    }
    display: flex;
    align-items: center;

    .avatar {
      width: 90rpx;
      height: 90rpx;
      border-radius: 45rpx;
    }

    > .right {
      margin-left: 20rpx;

      .nick-name {
        font-size: 34rpx;
        font-weight: 500;
        color: #fff5e9;
      }

      .member-status {
        margin-top: 8rpx;
        font-size: 28rpx;
        color: #aea7a1;
        display: flex;
        align-items: center;
      }
    }
  }

  .member-list-wrapper {
    transform: translateY(-30rpx);
    border-radius: 30rpx 30rpx 0 0;
    background: white;
    padding: 60rpx 30rpx;

    .member-list {
      display: flex;

      .member-item {
        width: 0;
        flex: 1;
        display: flex;
        justify-content: space-around;
        align-items: center;
        flex-direction: column;
        border-radius: 16rpx 16rpx 16rpx 16rpx;
        height: 300rpx;

        &:not(:last-child) {
          margin-right: 32rpx;
        }

        &.active {
          border: 8rpx solid #ffa441;
          background: linear-gradient(360deg, #ffe1c1 0%, #fff6e4 100%);

          > .average-price {
            color: #ff8000;
          }
        }

        &.inactive {
          background: #f6f6f6;
          border: 8rpx solid #f6f6f6;

          > .average-price {
            color: var(--text-color-light);
          }
        }

        > .title {
          font-size: 32rpx;
          font-weight: 500;
        }

        .price-container {
          display: flex;
          align-items: center;
          flex-direction: column;

          > .price {
            display: flex;
            align-items: flex-end;

            &:not(:first-child) {
              margin-top: 10rpx;
            }

            &.actual-price {
              color: #ff8000;

              > .unit {
                font-size: 28rpx;
              }

              > .number {
                font-size: 50rpx;
                line-height: 1;
              }
            }

            &.origin-price {
              color: var(--text-color-light);
              text-decoration: line-through;
              font-size: 30rpx;
            }
          }
        }

        > .average-price {
          font-size: 28rpx;
        }

        &.primary {
          background: #3e3e3e;
          border: 4rpx solid #ff9429;
          color: #ecd1b6;
        }
      }
    }

    .agreement {
      display: flex;
      align-items: center;
      margin-top: 30rpx;

      > .radio {
        transform: scale(0.7);
      }

      > .text {
        font-size: 30rpx;

        > .normal {
          color: var(--text-color-light);
        }

        > .primary {
          color: var(--text-color-theme);
        }
      }
    }
  }
}

.poster {
  margin-top: 15rpx;
  width: 100vw;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100vw;
  height: 130rpx;
  box-sizing: content-box;
  display: flex;
  align-items: center;
  background: white;
  padding-bottom: env(safe-area-inset-bottom);
  border-top: 2rpx solid var(--border-color);

  .total-price {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;

    > .content {
      display: flex;
      align-items: flex-end;
      line-height: 30rpx;

      > .text {
        font-size: 34rpx;
      }

      > .unit {
        font-size: 34rpx;
        color: #ff8000;
      }

      > .number {
        font-size: 56rpx;
        line-height: 44rpx;
        color: #ff8000;
      }
    }
  }

  .pay-btn {
    width: 300rpx;
    height: 90rpx;
    background: var(--theme-color);
    color: var(--text-color);
    font-size: 30rpx;
    border-radius: 45rpx;
    margin-right: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.swiper {
  width: 100vw;
}
</style>
